#include "time_tick.h"

void Delay_Us(const uint32_t delay) {
    const uint32_t tickstart = GetTick_Us();

    while (GetTick_Us() - tickstart < delay) {
    }
}

uint32_t GetTick_Us() {
    // 计算 1us 的时间应该减少多少次
    const uint32_t oneUsCount = (SysTick->LOAD + 1UL) / (1000U * HAL_GetTickFreq());

    // SysTick 是递减的，在此计算 SysTick 减了几次
    const uint32_t nowCount = SysTick->LOAD - SysTick->VAL;

    // SysTick 减少的次数除以 1us 应该减少的次数，等于 us 数
    return HAL_GetTick() * 1000U + nowCount / oneUsCount;
}
